/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package broadcast;
import BittorentPackage.BittorentPackageMessage;
import common.function_common;
import common.global;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;

public class BroadcastSender
{
  // Set a default listener port
  private int senderPort = 59;
  // set a 10 second UDP timeout
  private static int TIMEOUT = 10000;
  private DatagramSocket senderSocket = null;
  private static int MAX_PACKET_SIZE = 255;

  // Default Constructor
  public BroadcastSender()
  {
    super();
    senderPort = global.port;
    MAX_PACKET_SIZE = global.MAX_PACKET_SIZE;
    TIMEOUT = global.TIMEOUT;
  }

  // Alternate Constructor to Override Port
  public BroadcastSender( int newPort )
  {
    // overide port setting
    senderPort = newPort;
  }

  public void sendBroadcast( BittorentPackageMessage pk ) throws IOException
  {
    // Determine the actual size of the message
        try
        {
          byte[] buffer = function_common.serializeObject(pk);  
          // For this example, just send it to the local host
          InetAddress addr = InetAddress.getByName("192.168.227.255");
          
          // Create the packet of information
          DatagramPacket infoPacket =
            new DatagramPacket( buffer, buffer.length , addr, this.senderPort );
          senderSocket = new DatagramSocket();
          // Send the packet and clean up the resources
          global.sendMine = true;
          senderSocket.send( infoPacket );
          senderSocket.close();
        }
        catch( NotSerializableException ex )
        {
          System.out.println( "Problem creating socket on port: " + senderPort );
          System.exit( -1 );
        }
  }
}